#include <ioCC2540.h>
#include "epl_hal_spi.h"

/** \brief	Write one byte to SPI interface
*
* Write one byte to SPI interface
*
* \param[in]       write
*     Value to write
*/
void spiWriteByte(uint8 write)
{
        U1CSR &= ~0x02;                 // Clear TX_BYTE
        U1DBUF = write;
        while (!(U1CSR & 0x02));        // Wait for TX_BYTE to be set
}

/** \brief	Read one byte from SPI interface
*
* Read one byte from SPI interface
*
* \param[in]       read
*     Read out value
* \param[in]       write
*     Value to write
*/
void spiReadByte(uint8 *read, uint8 write)
{
        U1CSR &= ~0x02;                 // Clear TX_BYTE
        U1DBUF = write;
        while (!(U1CSR & 0x02));        // Wait for TX_BYTE to be set
        *read = U1DBUF;
}

/** \brief	Init SPI interface
*
* Init SPI interface
*
*/

void spiInit(){
    //*** Setup USART 1 SPI at alternate location 2 ***

    // USART 1 at alternate location 2
    PERCFG |= 0x02;
    // Peripheral function on SCK, MISO and MOSI (P1_5-7)
    P1SEL |= 0xE0;
    
    //*** Setup the SPI interface ***
    // SPI Master Mode 
    U1CSR &= ~0xA0;
    // Negative clock polarity, Phase: data out on CPOL -> CPOL-inv
    //                                 data in on CPOL-inv -> CPOL
    // MSB first
    U1GCR = 0x20;
    // SCK frequency = 1MHz 
    U1GCR |= 0x0F;
    U1BAUD = 0x00;
}